package com.jkkc.lib.base.util

import android.content.Context
import com.blankj.utilcode.util.ThreadUtils
import com.jkkc.lib.base.dialog.MiniDialog
import com.jkkc.lib.base.extend.runOnUiThreadDelayed

/**
 * Author:LiXian
 * <p>
 * Desc:线程任务工具类
 * Version:1.0
 * date 2023/2/28 16:50
 */
object ThreadTaskUtil {

    @JvmStatic
    fun <T> executeBySingleTask(doInBackground: () -> T, onSuccess: ((T) -> Unit)? = null, onFail: ((String) -> Unit)? = null) {
        val mTask = object : ThreadUtils.SimpleTask<T>() {
            override fun doInBackground(): T {
                return doInBackground.invoke()
            }

            override fun onSuccess(result: T) {
                onSuccess?.invoke(result)
                cancel()
            }

            override fun onFail(t: Throwable?) {
                super.onFail(t)
                onFail?.invoke(t?.message ?: "")
                cancel()
            }
        }
        ThreadUtils.executeBySingle(mTask)
    }

    @JvmStatic
    fun <T> executeBySingleTask(cancelTime: Int = 10, doInBackground: () -> T, onSuccess: ((T) -> Unit)? = null, onFail: ((String) -> Unit)? = null) {
        val mTask = object : ThreadUtils.SimpleTask<T>() {
            override fun doInBackground(): T {
                return doInBackground.invoke()
            }

            override fun onSuccess(result: T) {
                onSuccess?.invoke(result)
                cancel()
            }

            override fun onFail(t: Throwable?) {
                super.onFail(t)
                onFail?.invoke(t?.message ?: "")
                cancel()
            }
        }
        runOnUiThreadDelayed({ mTask.cancel() }, cancelTime * 1000L)
        ThreadUtils.executeBySingle(mTask)
    }

    @JvmStatic
    @JvmOverloads
    fun <T> executeBySingleTaskAndDialog(mContext: Context?, content: String = "", doInBackground: () -> T, onSuccess: ((T) -> Unit)? = null, onFail: ((String) -> Unit)? = null) {
        val dialog = mContext?.let { MiniDialog(mContext) }
        dialog?.showDialog(content)
        val mTask = object : ThreadUtils.SimpleTask<T>() {
            override fun doInBackground(): T {
                return doInBackground.invoke()
            }

            override fun onSuccess(result: T) {
                onSuccess?.invoke(result)
                dialog?.dismissDialog()
                cancel()
            }

            override fun onFail(t: Throwable?) {
                super.onFail(t)
                onFail?.invoke(t?.message ?: "")
                dialog?.dismissDialog()
                cancel()
            }
        }
        ThreadUtils.executeBySingle(mTask)
    }
}